import { useState } from 'react';
import {
  FooterToolbar,
  PageContainer,
  ProCard,
  ProForm,
  ProFormDependency,
  ProFormItem,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
} from '@ant-design/pro-components';
import { Button, message, Space } from 'antd';

import { queryUserDetail, saveOrUpdateUser } from '@/services/user-management';
import { queryRoleList } from '@/services/role-management';
import PermissionsTree from '../../role-management/detail/permissions-tree';
import useDetailType from '@/hooks/useDetailType';

type Option = {
  key: string;
  label: string;
  value: string;
  disabled?: boolean;
};

type FormUserItem = API.UserItem & { roleId: string };

const UserDetail: React.FC = () => {
  const { isModify, isRead, params, goBack, goReplace } =
    useDetailType<Record<'id', string | undefined>>();
  const [roleList, setRoleList] = useState<API.RoleItem[]>([]);

  const { id } = params;

  /**
   * 获取用户详情
   * @param userId
   */
  const getUserDetail = async (userId: string) => {
    const res = await queryUserDetail({ id: userId });
    if (!res.code && res.data) {
      const data: FormUserItem = {
        ...res.data,
        roleId: res.data?.roleDO?.id || '',
      };

      return data;
    }
    return {} as FormUserItem;
  };

  /**
   * 获取角色列表
   */
  const getRoleList = async () => {
    const res = await queryRoleList({
      pageNum: 1,
      pageSize: 100,
    });
    if (!res.code && res.data) {
      setRoleList(res.data.content);
      return res.data.content.map(
        (r): Option => ({
          key: r?.id,
          label: r?.name,
          value: r?.id,
        }),
      );
    }
    return [];
  };

  /**
   * 提交保存
   * @param value
   * @returns
   */
  const onFinish = async (value: API.UserDetailParams) => {
    console.log(value);
    if (isModify && id) {
      value.id = id;
    }
    const res = await saveOrUpdateUser(value);
    if (!res.code && res.data) {
      message.success('提交成功');
      goReplace('/system/user/list');
      return;
    }
    message.error(res.message || '提交失败');
  };

  /**
   * 初始化
   * @returns FormUserItem
   */
  const init = async () => {
    if (isModify && !!id) {
      return getUserDetail(id);
    }
    return {
      enable: 1,
    } as FormUserItem;
  };

  return (
    <PageContainer>
      <ProCard>
        <ProForm<FormUserItem>
          layout="horizontal"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 10 }}
          request={init}
          submitter={{
            render: (_, dom) => (
              <FooterToolbar
                extra={
                  <div style={{ textAlign: 'center', padding: '5px 0' }}>
                    {isRead ? (
                      <Button onClick={goBack}>返回</Button>
                    ) : (
                      <Space>
                        <Button onClick={goBack}>取消</Button>
                        {dom[1]}
                      </Space>
                    )}
                  </div>
                }
              />
            ),
          }}
          onFinish={onFinish}
        >
          <ProFormText
            name="username"
            label="账号"
            placeholder="请输入用户名"
            readonly={isRead || isModify}
            required
            rules={[
              {
                required: true,
                message: '请输入用户名',
              },
              {
                min: 3,
                message: '用户名长度3-20个字符',
              },
              {
                max: 20,
                message: '用户名长度3-20个字符',
              },
            ]}
          />
          <ProFormText.Password
            name="password"
            label="密码"
            placeholder="请输入密码"
            readonly={isRead}
            required
            fieldProps={{ autoComplete: 'new-password' }}
            rules={[
              {
                required: true,
                message: '请输入密码',
              },
              {
                min: 3,
                message: '密码长度3-20个字符',
              },
              {
                max: 20,
                message: '密码长度3-20个字符',
              },
            ]}
          />
          {isRead && (
            <ProFormText name="yumId" label="yumId" placeholder="请输入yumId" readonly={isRead} />
          )}
          <ProFormText
            name="nickName"
            label="用户名称"
            placeholder="请输入用户名称"
            readonly={isRead}
            rules={[
              {
                min: 3,
                message: '用户名称长度3-20个字符',
              },
              {
                max: 20,
                message: '用户名称长度3-20个字符',
              },
            ]}
          />
          <ProFormText
            name="email"
            label="邮箱"
            placeholder="请输入邮箱地址"
            readonly={isRead}
            rules={[
              {
                type: 'email',
                message: '请输入正确的邮箱地址',
              },
            ]}
          />
          <ProFormSwitch
            name="enable"
            label="是否启用"
            checkedChildren="是"
            unCheckedChildren="否"
            readonly={isRead}
            transform={(e: number | boolean) => ({ enable: e ? 1 : 0 })}
          />
          <ProFormSelect
            name="roleId"
            label="角色id"
            placeholder="请选择角色"
            readonly={isRead}
            request={getRoleList}
          />
          <ProFormDependency name={['roleId']}>
            {({ roleId }) => {
              const current = roleList.find((r) => r.id === roleId);
              return (
                current && (
                  <ProFormItem
                    label="角色权限"
                    name="resourceIds"
                    // ignoreFormItem
                    getValueProps={() => ({
                      value: current.resourceIds,
                    })}
                  >
                    <PermissionsTree readonly />
                  </ProFormItem>
                )
              );
            }}
          </ProFormDependency>
        </ProForm>
      </ProCard>
    </PageContainer>
  );
};

export default UserDetail;
